package com.px.handler;

import cn.hutool.core.util.CoordinateUtil;
import com.alibaba.fastjson2.JSON;
import com.px.common.core.redis.RedisCache;
import com.px.common.utils.DateUtils;
import com.px.framework.mqtt.handler.IMqttHandler;
import com.px.system.domain.AirportOsd;
import com.px.system.domain.CommonTopic;
import com.px.system.mapper.AirportOsdMapper;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.regex.Pattern;

import static com.px.framework.mqtt.model.TopicConst.*;
import static com.px.framework.mqtt.model.TopicConst.STATUS_SUF;

@Component
public class OsdMqttHandler extends IMqttHandler {


    @Autowired
    private AirportOsdMapper airportOsdMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Pattern bindTopicName() {
        return Pattern.compile("^thing/product/" + REGEX_SN + "/osd$");
    }

    //接收Osd定频数据
    @Override
    public void handler(String topic, MqttMessage mqttMessage) {
        String sn = topic.substring((BASIC_PRE + PRODUCT).length(),
                topic.indexOf(STATUS_SUF));
        CommonTopic ct = JSON.parseObject(mqttMessage.getPayload(), CommonTopic.class);

        int type = redisCache.getCacheObject(sn);
        //0机场
        if(0==type){
            AirportOsd airportOsd = new AirportOsd();
            if(ct.getData().containsKey("mode_code")){
                airportOsd.setSn(sn);
                airportOsd.setModeCode(ct.getData().containsKey("mode_code") ? ct.getData().getInteger("mode_code") : null);

                CoordinateUtil.Coordinate coordinate = CoordinateUtil.gcj02ToWgs84( ct.getData().getDouble("latitude"),ct.getData().getDouble("longitude")  );
                airportOsd.setLatitude(BigDecimal.valueOf(coordinate.getLng()));
                airportOsd.setLongitude(BigDecimal.valueOf(coordinate.getLat()));
                airportOsd.setRainfall(ct.getData().containsKey("rainfall") ? ct.getData().getString("rainfall") : null);
                airportOsd.setWindSpeed(ct.getData().containsKey("wind_speed") ? ct.getData().getString("wind_speed") : null);
                airportOsd.setEnvironmentTemperature(ct.getData().containsKey("environment_temperature") ? ct.getData().getString("environment_temperature") : null);
                airportOsd.setCreateTime(DateUtils.getNowDate());
                airportOsdMapper.insertAirportOsd(airportOsd);
            }
        }

        ;

        //3无人机
        if(3==type)
            ;


    }
}
